from common.base_model import BasicModelMixin, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin
from exts import db
from common import constant


# 库存成本计算 (移动加权平均）
def calculate_cost_price(before_num, before_cost_price, change_num, change_price):
    # before_num 库存为负数
    if before_num < 0:
        return change_price
    # 防止 before_num + add_num = 0
    if change_num == 0:
        return before_cost_price
    if before_num + change_num == 0:
        return 0
    # 价格为空判断
    if not before_cost_price:
        before_cost_price = 0

    return (before_num * before_cost_price + change_num * change_price) / (before_num + change_num)


class StorageRecord(BasicModelMixin, db.Model, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin):
    __tablename__ = 'storage_record'

    id = db.Column(db.Integer, primary_key=True)
    warehouse_id = db.Column(db.Integer, db.ForeignKey("warehouse.id"))
    warehouse = db.relationship("Warehouse")
    sku_id = db.Column(db.Integer, db.ForeignKey('sku.id'))
    sku = db.relationship("Sku")
    unit_id = db.Column(db.Integer, db.ForeignKey('unit.id'))
    unit = db.relationship("Unit")
    num = db.Column(db.DECIMAL(20, constant.COMMON_DECIMAL), default=0)

    # 库存成本单价(当前值)
    cost_price = db.Column(db.DECIMAL(20, constant.COMMON_DECIMAL), default=0)

    __table_args__ = (
        db.UniqueConstraint('warehouse_id', 'sku_id', 'unit_id'),
    )

    def update_cost_price(self, change_num, price):
        """增加或减少 来修改库存成本单价
        采购： 增加
        撤销采购： 减少
        采购退货：减少
        撤销采购退货：增加
        销售：不变
        撤销销售：不变
        销售退货：不变
        撤销销售退货：不变
        """
        self.cost_price = calculate_cost_price(
            self.num, self.cost_price,
            change_num, price
        )
